﻿using System;
using System.Net;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net.NetworkInformation;

namespace Zorbo
{
    public static class DnsHelper
    {
        public static void Resolve(string host, Action<String, IPHostEntry> callback) {
            try {
                Dns.BeginGetHostEntry(host,
                    (ar) => {
                        IPHostEntry ret = null;
                        try {
                            ret = Dns.EndGetHostEntry(ar);
                        }
                        catch (SocketException) { }
                        catch (Exception ex) { OnDnsError(host, ex); }
                        finally {
                            ((Action<String, IPHostEntry>)ar.AsyncState)(host, ret);
                        }

                    }, callback);
            }
            catch (SocketException) { 
                callback(host, null);
            }
            catch (Exception ex) { 
                OnDnsError(host, ex);
                callback(host, null);
            }
        }

        public static void Resolve(IPAddress ip, Action<IPAddress, IPHostEntry> callback) {
            IPAddress tmpip = new IPAddress(ip.GetAddressBytes());

            try {
                Dns.BeginGetHostEntry(tmpip,
                    (ar) => {
                        IPHostEntry ret = null;

                        try {
                            ret = Dns.EndGetHostEntry(ar);
                        }
                        catch (SocketException) { }
                        catch (Exception ex) { OnDnsError(tmpip, ex); }
                        finally {
                            ((Action<IPAddress, IPHostEntry>)ar.AsyncState)(tmpip, ret);
                        }

                    }, callback);
            }
            catch (SocketException) {
                callback(tmpip, null);
            }
            catch (Exception ex) {
                OnDnsError(tmpip, ex);
                callback(tmpip, null);
            }
        }


        private static void OnDnsError(string host, Exception ex) {
#if DEBUG
            Console.WriteLine("Dns Error ({0}): {1}", host, ex.Message);
#endif
            if (DnsError != null) DnsError(host, ex);
        }

        private static void OnDnsError(IPAddress ip, Exception ex) {
            OnDnsError(ip.ToString(), ex);
        }


        public static event DnsErrorHandler DnsError;
        public delegate void DnsErrorHandler(String hostAddress, Exception ex);
    }
}
